<template>
  <div class="app-container">
    <!-- 用户信息展示 -->

    <!-- 课程信息表单 -->
    <el-form 
      :model="form"
      ref="form" 
      :rules="rules" 
      class="demo-ruleForm">
      <el-form-item 
        label="课程名称" 
        prop='name'
        :label-width="formLabelWidth">
        <el-input v-model="form.name"
          maxlength="20"
          show-word-limit 
          autocomplete="off">
        </el-input>
      </el-form-item>
      
      <el-form-item 
        label="标签" 
        :label-width="formLabelWidth">
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedTags" @change="handleCheckedTagsChange">
          <el-checkbox v-for="tag in tag_list" :label="tag.id" :key="tag.id">{{tag.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item
        label="头图"
      >
      
      </el-form-item>

      <el-form-item
        label="作者"
        prop='author'
      >
        <el-input v-model.number="form.author" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="种类" :label-width="formLabelWidth">
        <el-select v-model="form.category" placeholder="请选择种类">
          <el-option label="免费" value="免费"></el-option>
          <el-option label="限免" value="限免"></el-option>
          <el-option label="会员" value="会员"></el-option>
          <el-option label="训练营" value="训练营"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="价格"
        prop='price'
      >
        <el-input type="price" v-model.number="form.price" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="是否上架" :label-width="formLabelWidth">
        <el-radio-group v-model="form.is_online">
          <el-radio-button label="0">即将上架</el-radio-button>
          <el-radio-button label="1">已上架</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-form-item label="描述" prop='desc'>
          <el-input type="textarea" v-model="form.desc" :autosize="{ minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form-item>
    </el-form>

    <el-form :model="sectionForm" ref="sectionForm" label-width="100px" class="demo-dynamic">
      <el-form-item
        v-for="(section, index) in sectionForm.sections"
        :key="section.key"
        :prop="'sections.' + index + '.value'"
        :rules="{
          required: true, message: '章节名不能为空', trigger: 'blur'
        }"
      >
        <el-input v-model="section.value">
          <template slot="prepend">{{ '第' + (index + 1) + '节' }}</template>
          
          <el-button slot="append" @click.prevent="removeSection(section)">删除</el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="addSection">新增章节</el-button>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" :loading="submit_loading">确 定</el-button>
    </div>

  </div>
</template>

<script>
import { tags_get, username_post, get_course_all, course_info_put, course_info_delete, course_info_post } from "../axios_api/api"
import { getList } from '@/api/table'
import { constants } from 'zlib';

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      // 标签列表
      checkedTags:[],
      tag_list:[],
      sectionForm: {
          sections: [{
            value: ''
          }]
        },
      // 数据验证
      rules:{
        name:[
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 3, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        price:[
          { required: true, message: '价格不能为空'},
          { type: 'number', message: '价格必须是数字'}
        ],
          
        desc:[
          { required: true, message: '描述不能为空'},
        ],

        author:[
          { required: true, message: '作者不能为空'},
        ]
      },
      list: null,
      listLoading: true,
      discription: true,
      // 用户列表变量
      course_list: [],
      // vip变量
      vipdatas: {},
      // 管理员名
      username: localStorage.getItem("username"),
      // 弹窗变量
      UpdateUser: false,
      AddUser: false,
      DeleteUser: false,
      datas: {},
      // 分页
      total: 0,
      page: 1,
      size: 10,
      multipleSelection: [],
      // 表单开关
      dialogFormVisible: false,
      // 表单数据
      form: {
        },
      // 表单宽度
      formLabelWidth:"400",
      // 表单加载动态效果
      submit_loading: false
    }
  },
  mounted() {
    this.get_tags()
  },
  methods: {
    // 标签复选框
    handleCheckAllChange(val) {
      this.checkedTags = val ? tagOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedTagsChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.tag_list.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tag_list.length;
      console.log(this.checkedTags)
    },
    // 获取标签列表
    get_tags(){
      tags_get().then(resp=>{
        this.tag_list = resp.data
      })
    },
    removeSection(item) {
      var index = this.sectionForm.sections.indexOf(item)
      if (index !== -1) {
        this.sectionForm.sections.splice(index, 1)
      }
    },
    addSection() {
      this.sectionForm.sections.push({
        value: '',
        key: Date.now()
      });
    },
    // 提交
    submit(){
      // 判断大表单输入格式
      this.$refs.form.validate((valid) => {
          if (valid) {
            // 判断标签
            if(this.checkedTags.length==0){
              this.$message('请选择标签')
              return false
            }
            // 判断章节表单输入格式
            this.$refs.sectionForm.validate((valid)=>{
              if(valid){
                // 检查用户是否存在
                var author = {username:this.form.author}
                username_post(author).then(resp=>{
                  // 存在则给form赋值
                  if(resp.code==200){
                    this.form['uid'] = resp.uid
                    // 请求后端接口入库
                    var data = {course:this.form, section:this.sectionForm, tags:String(this.checkedTags)}
                      course_info_post(data).then(resp=>{
                        if(resp.code==200){
                          this.$message(resp.message)
                          this.$router.push('/form/course')
                        }
                      })
                  }else{
                    // 用户名不存在
                    this.$message('该用户不存在')
                    return false
                  }
                })
              }else{
                // 章节表单输入格式错误
                console.log('error submit!!');
                return false;
              }
            })
          } else {
            // 大表单输入格式错误
            console.log('error submit!!');
            return false;
          }
        });
    },
  },
  filters:{
    date_time(value){
      return value.split('T').join(' ').split('.')[0]
    },
    online(value){
      if(value=='0'){
        return '即将上架'
      }else{
        return '已上架'
      }
    }
  }
}
</script>

